package com.zjw.demo.vertx.starter.core;

import com.zjw.demo.vertx.starter.annotation.NonNull;
import com.zjw.demo.vertx.starter.config.ApplicationConfig;
import com.zjw.demo.vertx.starter.core.ioc.IOCScope;
import com.zjw.demo.vertx.starter.plugin.PluginDispatcher;
import com.zjw.demo.vertx.starter.router.RouterDispatcher;
import com.zjw.demo.vertx.starter.service.ServiceDispatcher;
import com.zjw.demo.vertx.starter.utils.LogUtils;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;

/**
 * 参考<a href="https://vertx.io/docs">...</a>
 */
public class VertxWebApplication {

  @NonNull
  private final HttpServer httpServer;
  @NonNull
  private final Router router;

  public static void run(Class<?> rootClass) {
    new VertxWebApplication(rootClass).listen();
  }

  public VertxWebApplication(Class<?> rootClass) {
    /*注册application到反射中*/
    Reflector.attachApplication(rootClass);

    /*注册配置*/
    ApplicationConfig.initConfig();

    /*创建唯一App*/
    Vertx vertx = Vertx.vertx();
    Reflector.attachVertx(vertx);

    /*启动各类Service*/
    ServiceDispatcher.dispatchService(vertx);

    /*创建HTTP服务*/
    httpServer = vertx.createHttpServer();

    /*创建应用路由*/
    router = Router.router(vertx);

    RouterDispatcher.dispatchRouter(router);

    //last is plugin
    PluginDispatcher.dispatchPlugin();

    if (Reflector.openIOC) {
      IOCScope.globalScope.refresh(Reflector.PROJECT_ROOT_PACKAGE_NAME);
    }
  }

  public void listen() {
    /*设置路由，监听8888端口*/
    int port = ApplicationConfig.getInt("http.port");
    httpServer.requestHandler(router).listen(port, http -> {
      if (http.succeeded()) {
        /*监听成功*/
        LogUtils.debug("Start", "HTTP server started on port " + port);
      } else {
        /*监听失败*/
        LogUtils.error("Start", "HTTP server error");
      }
    });
  }
}
